package com.wudao.ncmplay.resolver;

import com.wudao.ncmplay.config.NcmProperties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Locale;

@Component
public class I18nMessageUtil
{
    private static final Logger LOGGER = LogManager.getLogger(I18nMessageUtil.class);

    @Resource
    private MessageSource messageSource;

    @Resource
    private NcmProperties ncmProperties;

    /**
     * @Description 根据key获取系统默认语言的数据
     *
     * @author ZhengGuoFen
     * @Date  2022/6/14
     * @param key
     * @return
     **/
    public String getMessage(String key){
        try {
            String lang = ncmProperties.getLang();
            String[] langArr = lang.split("_");
            Locale locale = new Locale(langArr[0], langArr[1]);
            return messageSource.getMessage(key, null, locale);
        }catch (NoSuchMessageException e){
            LOGGER.error("获取国际化资源失败", e);
        }
        return key;
    }

    /**
     * @Description 根据key和locale获取国际化
     *
     * @author ZhengGuoFen
     * @Date  2022/6/14
     * @param key
     * @param locale
     * @return
     **/
    public String getMessage(String key, Locale locale){
        try {
            return messageSource.getMessage(key, null, locale);
        }catch (NoSuchMessageException e){
            LOGGER.error("获取国际化资源失败", e);
        }
        return key;
    }

    /**
     * @Description 根据key和替代参数获取国际化资源
     *
     * @author ZhengGuoFen
     * @Date  2022/6/14
     * @param key
     * @param values 替代参数
     * @return
     **/
    public String getMessage(String key, @Nullable Object[] values){
        try {
            String lang = ncmProperties.getLang();
            String[] langArr = lang.split("_");
            Locale locale = new Locale(langArr[0], langArr[1]);
            return messageSource.getMessage(key, values, locale);
        }catch (NoSuchMessageException e){
            LOGGER.error("获取国际化资源失败", e);
        }
        return key;
    }

    /**
     * @Description 根据key和替代参数和locale获取国际化资源
     *
     * @author ZhengGuoFen
     * @Date  2022/6/14
     * @param key
     * @param values 替代参数
     * @param locale
     * @return
     **/
    public String getMessage(String key, @Nullable Object[] values, Locale locale){
        try {
            return messageSource.getMessage(key, values, locale);
        }catch (NoSuchMessageException e){
            LOGGER.error("获取国际化资源失败", e);
        }
        return key;
    }
}
